package uk.ac.glasgow.oose2.gcf.view.lui.tests;

import static org.junit.Assert.assertEquals;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;

import org.junit.Before;

public abstract class LuiHarness {

	/* Gain access to the stdin/stdout process interface */
	protected PrintWriter writeToStdIn;
	protected BufferedReader readFromStdOut;
	
	@Before
	public void setUp()  throws IOException {
		
		///redirect the test's I/O so it can be written to/read via try command.
		
		PipedInputStream redirectedStdIn = new PipedInputStream();
		PipedOutputStream pos = new PipedOutputStream(redirectedStdIn);
		writeToStdIn = new PrintWriter(pos);		
		System.setIn(redirectedStdIn);
		
		PipedInputStream pis = new PipedInputStream();
		PrintStream redirectedStdOut = new PrintStream(new PipedOutputStream(pis));
		readFromStdOut = new BufferedReader(new InputStreamReader(pis));
		System.setOut(redirectedStdOut);
	}
	
	/**
	 * Utility interaction method for testing command sequences
	 * 
	 * @param command
	 *            a sequences of commands to make available for reading on stdin
	 * @param expected
	 *            a sequence of lines that should be printed on stdout
	 * @throws IOException
	 *             if an error occurs while interacting with LuiBasic via
	 *             redirected stdin and stdout.
	 */
	protected final void tryCommand(String command, String... expected) throws IOException{
		writeToStdIn.println(command);
		writeToStdIn.flush();
		
		for (String expect: expected){
			String result = readFromStdOut.readLine();
			assertEquals(command,expect,result);
		}
	}
}
